package com.zgl.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zgl.feign.entity.MailEntity;
import com.zgl.feign.service.FeignMessageService;
import com.zgl.modules.user.entity.CodeEntity;
import com.zgl.modules.user.entity.User;
import com.zgl.modules.user.mapper.CodeMapper;
import com.zgl.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
@Service
public class CodeServiceImpl {
    @Resource
    CodeMapper codeMapper;
    @Resource
    private FeignMessageService feignMessageService;
    public R saveOne(CodeEntity codeEntity) {
        if (codeMapper.insert(codeEntity) == 1) {
            return R.success();
        } else {
            return R.error();
        }

    }

    public R removeOne(String id) {
        if (codeMapper.deleteById(id) == 1) {
            return R.success();
        } else {
            return R.error();
        }
    }
    public R getOne(String id) {
        CodeEntity codeEntity=codeMapper.selectById(id);
        return R.success(codeEntity);
    }

    public R modifyOne(CodeEntity codeEntity) {
        if(codeMapper.updateById(codeEntity)==1){
            return R.success();
        }else {
            return  R.error();
        }
    }
    @Transactional
    public R getcode(@RequestParam(value = "mail", required = true)String mail){
        int code= (int) ((Math.random() * 9 + 1) * 100000);
        CodeEntity codeEntity=codeMapper.selectById(mail);
        if (codeEntity==null){
            codeMapper.insert(new CodeEntity(mail,code,0));
        }else if (codeEntity!=null){
            if(codeEntity.getUsed()==1){ return R.error("该邮箱已被注册");}
            codeEntity.setValue(code);
            codeMapper.updateById(codeEntity);
        }
        String text="验证码是【"+code+"】,如果不是本人操作请忽略";
        MailEntity mailEntity=new MailEntity(mail,"验证码",text);
        return feignMessageService.sendMail(mailEntity);
    }
}